import { Dropdown, MenuProps, Space } from 'antd';
import { DropdownProps } from 'antd/es/dropdown/dropdown';
import React, { useEffect, useState } from 'react';
import { useMatches } from 'react-router-dom';

import { SvgIcon } from '@/components/icon';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useDatasetFlag } from '@/store/configStore';
import { useConfig } from '@/store/configStore';
import { useRoleManage } from '@/store/roleManageStore';
import { useUserInfo } from '@/store/userStore';

import { useMenuItems } from './MenuList';

function RouterMenu() {
  const matches = useMatches();
  const { isPc } = useWindowWidth();
  const datasetFlag = useDatasetFlag();
  const [currentMenu, setCurrentMenu] = useState<MenuProps['items'][number] | undefined>(undefined);
  const [isAdmin, setIsAdmin] = useState(true);
  const { role } = useUserInfo();
  const { id } = useConfig();
  const { isEnableRoleConditions } = useRoleManage();

  const { itemList, itemList2 } = useMenuItems(isEnableRoleConditions, datasetFlag, id);

  const menuStyle: React.CSSProperties = {
    boxShadow: 'none',
    borderRadius: '10px',
    backgroundColor: '#f4f5fc',
    border: '2px solid #eee',
  };

  const dropdownRender: DropdownProps['dropdownRender'] = (menu) => (
    <div>{React.cloneElement(menu as React.ReactElement, { style: menuStyle })}</div>
  );

  useEffect(() => {
    const paths = matches.filter((item) => item.pathname !== '/').map((item) => item.pathname);
    const menu = itemList.find((item) => paths.some((path) => path.startsWith(item?.key)));
    setCurrentMenu(menu);
  }, [matches]);

  useEffect(() => {
    role?.code && setIsAdmin(role?.code === 'admin' || role?.code?.includes('admin'));
  }, [role]);

  return (
    <div style={{ paddingLeft: '20px' }}>
      <Dropdown
        trigger={isPc ? ['hover'] : ['click']}
        // className="w-[140px]"
        dropdownRender={dropdownRender}
        menu={{
          items: isAdmin ? itemList : itemList2,
        }}
      >
        <Space>
          {currentMenu?.icon}
          <span style={{ fontSize: '16px' }}>{currentMenu?.label}</span>
          <SvgIcon icon="ri--arrow-down-s-fill" size={20} />
        </Space>
      </Dropdown>
    </div>
  );
}

export default RouterMenu;
